<template>
	<!-- 话题详情 -->
	<view class="container">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="navBorder" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<view class="title">
				<view class="flex-r ac" v-if="barInfo && barInfo.logo && barInfo.title" @tap="$CHS.goBarHome(barInfo.barId)">
					<lazy-image class="bar-avatar" :src="barInfo.logo+'?imageView2/1/w/100/h/100/q/50'" type="bar" fit="cover"></lazy-image>
					<text class="text-large">{{barInfo.title}}</text>
				</view>
				<text v-else>详情</text>
			</view>
			<template slot="right">
			</template>
		</uni-nav-bar>
		<template v-if="!articleDetail.error">
			<scroll-view
				class="scroll-Y" 
				:style="scrollHeight"
				:scroll-y="true"
				:refresher-enabled="true" 
				:refresher-triggered="refreshing"
				refresher-default-style="none" 
				refresher-background="rgba(255, 255, 255, 0)"
				@refresherrefresh="refresh"
				@scroll="scroll"
			>
			<view class="body">
				<view class="post-des card flex-c">
					<view class="post-des-title thinborder">
						<view class="title-name">
							{{articleDetail.title}}
						</view>
						<view class="text-info color-grey flex-r ac jsb">
							<view class="date" v-if="articleDetail.createTime">
								<uni-dateformat :date="articleDetail.createTime" :threshold="[60000, 12*3600000]" format="MM-dd hh:mm"></uni-dateformat>
								{{new Date() - new Date(articleDetail.createTime.replace(/-/ig, '/')) < 12*3600000 ? '发布' : ''}}
							</view>
							<text class="views">{{articleDetail.virtualReadNum || 0}}人查看</text>
						</view>
					</view>
					<view class="post-des-head flex-r ac" @tap="$CHS.goExpertHome(articleDetail.userId, articleDetail.userType, articleDetail.type)">
						<view class="author-image border-round">
							<lazy-image class="inheritwh border-round" :src="articleDetail.userAvatar+'?imageView2/1/w/100/h/100/q/50'" :type="articleDetail.userType" fit="cover"></lazy-image>
						</view>
						<view class="author-info flex-c">
							<text class="text-regular">{{articleDetail.userName}}</text>
						</view>
						<view class="author-fav flex-c" v-if="articleDetail.userType == 'expert'">
							<button class="favbtn active-msg" :class="{'nochat': articleDetail.userIdentity != 1}" type="warn" size="mini" v-if="articleDetail.followStatus == 1" @tap.stop="$CHS.goChat(articleDetail.userId, articleDetail.userIdentity)">私信</button>
							<button class="favbtn active-fav" type="warn" size="mini" @tap.stop="favExpert(articleDetail.userId)" v-else>关注</button>
						</view>
					</view>
					<view class="post-detail-body mt20">
						<view class="item-body-text" v-if="articleDetail.content">
							<view class="html-content" ref="freeContent" v-html="articleDetail.content"></view>
						</view>
						<view class="item-body-video" v-if="articleDetail.videoUrl" @tap="videoPlay(dynamicId, articleDetail.videoUrl)">
							<FullVideo :url="articleDetail.videoUrl" :article="true" width="710rpx" height="400rpx" buttonWidth="120rpx"></FullVideo>
						</view>
					</view>
					<view class="post-detail-vote flex-c ac" v-if="articleDetail.type == 7">
						<view class="progress-box flex-r ac jsb mt20" v-for="(vote, index) in articleDetail.discussOption" :key="index" :class="{'active': !vote.voteFlag}" @tap="voteSubmit(index)">
							<view class="progress" :style="'width:' + (articleDetail.participateNum ? vote.voteNum / articleDetail.participateNum * 100 : 0) + '%;'"></view>
							<view class="left flex-r ac">
								<text class="text-regular text-hidden two">{{vote.title}}</text>
								<image class="select-icon" src="@/public/images/bar/wxd.png" mode="aspectFit" v-if="vote.voteFlag"></image>
							</view>
							<text class="text-secondary">{{vote.voteNum}}</text>
						</view>
					</view>
					<view class="post-detail-join mt20 flex-r ac jsb" v-if="articleDetail.participateNum && articleDetail.participateAvatar">
						<view class="join-user flex-r ac" :style="'width: '+[(articleDetail.participateAvatar.length - 1)*40 + 64]+'rpx;'">
							<lazy-image
								v-for="(avatar, index) in articleDetail.participateAvatar.slice(0, 5)"
								:key="index" 
								class="user-avatar border-round" 
								:style="'z-index: '+(5-index)+';left:'+(index*40)+'rpx;'" 
								:src="avatar"
								type="user"
								fit="cover"
							></lazy-image>
						</view>
						<text class="text-small color-grey">{{articleDetail.participateNum}}人已参与{{articleDetail.type == 6 ? '话题讨论' : '投票'}}</text>
					</view>
				</view>
				<view class="post-comment" v-if="articleDetail.type">
					<CommentList
						:type="articleDetail.type+1" 
						:msgId="dynamicId" 
						:barId="barInfo && barInfo.barId" 
						:refresh="refreshing" 
						@more="showCommentPopup = true"></CommentList>
				</view>
			</view>
			</scroll-view>
			<!-- <ScrollPush v-if="articleDetail.type" :barId="barInfo && barInfo.barId" :msgId="dynamicId" :type="articleDetail.type+1" @click="showCommentPopup = true"></ScrollPush> -->
			<template v-if="articleDetail.type">
				<view class="foot">
					<CommentInput 
						:popup.sync="inputPopup"
						:type="articleDetail.type+1" 
						:commentType="1" 
						:articleId="dynamicId" 
						:expertId="articleDetail.userId" 
						@success="commentSuccess"></CommentInput>
				</view>
				<CommentPopup
					:show.sync="showCommentPopup" 
					:type="articleDetail.type+1" 
					:msgId="dynamicId" 
					:expertId="articleDetail.userId" 
					:barId="barInfo && barInfo.barId" 
					:refresh="refreshing">
				</CommentPopup>
			</template>
		</template>
		<EmptyContent v-else top="250rpx" text="暂无数据" img="qsy_zwxl" :showRefresh="articleDetail.error" @refresh="getDiscussDetail(dynamicId)"></EmptyContent>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dynamicId: null, //帖子ID
				articleDetail: { //内容详情
					error: false
				},
				
				navBorder: false, //导航栏下边框
				refreshing: false, //下拉刷新状态
				
				barInfo: null, //球吧信息
				showCommentPopup: false, //评论列表弹窗状态
				inputPopup: false, //评论输入框弹窗状态
				
			}
		},
		components: {
			CommentList: () => import('./components/ch-comment/ch-commentlist.vue'), //自定义评论列表
			CommentPopup: () => import('./components/ch-comment/ch-commentpopup.vue'), //自定义评论列表弹窗
			CommentInput: () => import('./components/ch-comment/ch-commentinput.vue'), //留言输入框
			ScrollPush: () => import("@/components/ch-scroll/ch-scrollpush.vue"),
		},
		computed: {
			user() { //用户信息
				return this.$store.state.user
			},
			scrollHeight() { //页面高度
				return `height:calc(var(--safe-height) - var(--navbar-height) - 96rpx);`;
			},
			canLeave() { //是否可以直接退出页面
				return !this.showCommentPopup && !this.inputPopup
			}
		},
		watch: {
			"articleDetail.content"(newValue, oldValue) { //富文本图片添加点击预览
				if(newValue){
					let imageList = this.getImgList(newValue)
					this.$nextTick(()=>{
						setTimeout(() => {
							this.addPreviewImage("freeContent", imageList)
						}, 500)
					})
				}
			}
		},
		onLoad() {
			let {did, barId, barName, barLogo} = this.$Route.query
			this.dynamicId = did
			if(this.dynamicId){
				if(barId){
					this.barInfo = {
						barId,
						logo: barLogo,
						title: barName
					}
				}
				this.getDiscussDetail(this.dynamicId)
			}else{
				console.log('非法请求');
				this.$CHS.errorRequest('index', '数据请求错误，请返回重试')
			}
			window.addEventListener("error", this.$CHS.imageLoadError, true)
		},
		beforeRouteLeave(to, from, next) {
			if(this.canLeave || to.name == 'experthome' || to.name == 'memberhome'){
				next();
			}else{
				if(this.showCommentPopup){
					this.showCommentPopup = false
				}else if(this.inputPopup){
					this.inputPopup = false
				}
				next(false);
			}
		},
		onUnload() {
			window.removeEventListener("error", this.$CHS.imageLoadError, true)
		},
		methods: {
			//页面滑动监听
			scroll(e) {
				if(e.detail.scrollTop > 10){
					this.navBorder = true
				}else{
					this.navBorder = false
				}
			},
			//下拉刷新
			refresh() {
				//更新刷新状态，加载数据
				this.refreshing = true
				this.getDiscussDetail(this.dynamicId)
				setTimeout(() => {
					this.refreshing = false
				}, 800)
			},
			//动态晒单详情
			getDiscussDetail(dynamicId) {
				this.$http.get({
					url: '/api/user/dynamic/info',
					data: {
						dynamicId,
						forumId: this.barInfo && this.barInfo.barId
					}
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						this.articleDetail = data.result
						//更新列表阅读数量
						uni.$emit('readNum', {num: data.result.virtualReadNum})
						//处理IOS多余Html代码
						if(data.result.content){
							this.articleDetail.content = this.$CHS.filterRichText(data.result.content)
						}
						if(this.articleDetail.content){
							this.articleDetail.content = this.articleDetail.content.replace(/width="[3-9][4-9][0-9]"/ig, '')
							// if(this.articleDetail.videoUrl){
							// 	this.articleDetail.content=this.articleDetail.content.replace(/<img.*?>/g, '');
							// 	console.log(this.articleDetail.content,'内容')
							// }
						}
					}else{
						this.$ShowToast({text: data.message || '讨论帖详情加载失败', type: 2})
						this.articleDetail.error = true
						/* setTimeout(()=>{
							this.$goBack(1)
						}, 1000) */
					}
				}).catch((err) => {
					console.log(err);
					this.articleDetail.error = true
				})
			},
			// 提取图片
			getImgList(newValue) {
				let imgReg = /<img.*?(?:>|\/>)/gi; //匹配图片中的img标签
				let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配图片中的src
				let arr = newValue.match(imgReg); //筛选出所有的img
				let srcArr = [];
				if(arr){
					arr.forEach(item => {
						let src = item.match(srcReg);
						srcArr.push(src[1]);
					})
				}
				return srcArr
			},
			//图片预览
			addPreviewImage(refId, imageList){
				let contentDom = this.$refs[refId]?.$el
				if(contentDom){
					contentDom.addEventListener('click', (e) => {
						if(e.target.tagName.toUpperCase() == "IMG" && e.target.width > 50){
							uni.previewImage({
								current: e.target.currentSrc,
								urls: imageList,
								loop: true
							});
						}
					});
				}
			},
			//关注专家
			favExpert(eid) {
				if(!this.$store.state.isLogin){
					this.$CHS.goUserLogin()
					return
				}
				if(eid === this.isFaving){ //防止重复提交
					return
				}else{
					this.isFaving = eid
					this.$CHS.favExpert(eid).then( res => {
						console.log(res);
						this.articleDetail.followStatus = 1
					}).catch(err => {
						console.log(err);
						this.articleDetail.followStatus = 2
					}).finally(()=>{
						this.isFaving = null
					})
				}
			},
			//投票
			voteSubmit(index) {
				if(!this.$store.state.isLogin){
					this.$CHS.goUserLogin()
					return
				}
				if(this.isSubmit){
					return
				}
				let vote = this.articleDetail.discussOption
				let status = vote.every(item => !item.voteFlag)
				if(status){
					this.isSubmit = true
					this.$http.post({
						url: '/api/chtyForumDiscussRecord/add',
						data: {
							id: vote[index].id,
							status: 1
						}
					}).then(data => {
						console.log(data);
						if(data.success){
							this.$ShowToast({text: '投票成功', type: 1})
							this.articleDetail.participateNum = this.articleDetail.participateNum + 1
							this.articleDetail.participateAvatar.unshift(this.user.avatar)
							this.articleDetail.participateAvatar = this.articleDetail.participateAvatar.slice(0, 5)
							vote[index].voteFlag = true
							vote[index].voteNum = Number(vote[index].voteNum) + 1
						}else{
							this.$ShowToast({text: data.message || '投票失败，请稍后重试', type: 2})
						}
					}).finally(()=>{
						this.isSubmit = false
					})
				}else{
					uni.showToast({
						title: '您已完成投票',
						icon: 'none'
					})
				}
			},
			//视频播放
			videoPlay(aid, path) {
				if(path.indexOf(this.$store.state.videoDomain) > -1){
					path = path.substr(this.$store.state.videoDomain.length + 1)
				}
				let params = {aid, path}
				this.$Router.push({ name: 'videoplay', params })
			},
			//评论发布成功
			commentSuccess() {
				this.refreshing = true
				setTimeout(() => {
					this.refreshing = false
				}, 800)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		position: relative;
		.scroll-Y{
			/deep/ .uni-scroll-view-content{
				padding-top: 10rpx;
				height: calc(100% - 10rpx);
			}
		}
	}
	.body{
		padding: 10rpx 0 20rpx;
	}
	.card{
		background: #FFFFFF;
		margin-bottom: 20rpx;
		padding: 40rpx 20rpx;
	}
	.post-des{
		padding-top: 30rpx;
		margin-bottom: 0;
		.post-des-title{
			padding-bottom: 30rpx;
			//box-shadow: 0px 1rpx 0px 0px #EDEDED;
			.title-name{
				font-size: 36rpx;
				font-weight: 500;
				line-height: 54rpx;
				word-break: break-all;
			}
			.text-info{
				margin-top: 20rpx;
				.views{
					flex: 2;
					text-align: right;
				}
			}
		}
		.post-des-head{
			margin-top: 20rpx;
			.author-image{
				position: relative;
				width: 80rpx;
				height: 80rpx;
				background-color: #FFFFFF;
				background-size: 100%;
			}
			.author-info{
				flex: 2;
				width: 400rpx;
				margin-left: 20rpx;
				.info-detail{
					max-width: 400rpx;
					margin-top: 18rpx;
					font-size: 22rpx;
					color: #999999;
					line-height: 24rpx;
					overflow: hidden;
					text-overflow:ellipsis;
					white-space: nowrap;
				}
			}
			.author-fav{
				.favbtn{
					width: 120rpx;
					height: 60rpx;
					border-radius: 30rpx;
					font-size: 24rpx;
					padding: 0;
					margin: 0;
					box-sizing: border-box;
					&.active-fav{
						color: #0055FF;
						background: #E5EEFF;
						line-height: 60rpx;
						border: none;
					}
					&.active-msg{
						color: #0055FF;
						background: #FFFFFF;
						border: 2rpx solid #0055FF;
						line-height: 56rpx;
					}
					&.nochat{
						border-color: #99BBFF;
						color: #99BBFF;
					}
				}
			}
		}
		.post-detail-body{
			font-size: 30rpx;
			line-height: 52rpx;
			/deep/ .html-content{
				p:first-child, div:first-child{
					margin-top: 0;
				}
				p:last-child, div:last-child{
					margin-bottom: 0;
				}
			}
			.item-body-video{
				margin-top: 18rpx;
				max-width: 710rpx;
				max-height: 400rpx;
				border-radius: 8rpx;
				/deep/ .playIcon{
					width: 120rpx;
				}
			}
		}
		.post-detail-vote{
			.progress-box{
				width: 100%;
				position: relative;
				height: 88rpx;
				padding: 0 30rpx;
				background: #FFFFFF;
				border: 1rpx solid #0055FF;
				border-radius: 10rpx;
				box-sizing: border-box;
				overflow: hidden;
				color: #0055FF;
				.progress{
					position: absolute;
					left: 0;
					top: 0;
					bottom: 0;
					background: #E5EFFF;
					z-index: 1;
				}
				.left{
					z-index: 2;
					max-width: 450rpx;
					margin-right: 10rpx;
					.select-icon{
						flex: 1;
						margin-left: 15rpx;
						min-width: 32rpx;
						width: 32rpx;
						height: 32rpx;
					}
				}
				text{
					z-index: 2;
				}
				&.active{
					border-color: #999999;
					text{
						color: #333333;
					}
					.progress{
						background: #E6E6E6;
					}
				}
			}
		}
		.post-detail-join{
			.join-user{
				position: relative;
				height: 64rpx;
				margin-right: 40rpx;
				.user-avatar{
					width: 64rpx;
					height: 64rpx;
					border: 4rpx solid #FFFFFF;
					box-sizing: border-box;
					position: absolute;
				}
			}
		}
	}
	.post-other{
		margin-top: 50rpx;
		.post-other-head{
			align-items: center;
			justify-content: space-between;
			color: #333333;
			.head-left{
				line-height: 36rpx;
				font-size: 36rpx;
				font-weight: bold;
			}
			.head-right{
				height: 28rpx;
				align-items: center;
				font-size: 30rpx;
				font-weight: 400;
			}
		}
		.post-other-hot{
			/deep/ .article-list-item:last-child{
				margin-bottom: 0;
			}
			/deep/ .expert-share-list{
				padding: 30rpx 0 0;
			}
			/deep/ .expert-share-item:last-child{
				margin-bottom: 0;
			}
		}
	}
	.foot{
		max-width: $max-width;
		margin: $pc-margin;
		z-index: 997;
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		background: #FFFFFF;
		padding-bottom: var(--safe-area-inset-bottom);
	}
</style>
